#pragma once
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/time.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/stat.h>
#include<cstdio>
#include<cstring>
#include<fcntl.h>
#include<signal.h>
#include<pthread.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<vector>
#include<arpa/inet.h>
#include<sys/wait.h>
#include<functional>
#include <semaphore.h>
#include<jsoncpp/json/json.h>
#include<sys/select.h>
using namespace std;
#include"Log.hpp"
#define P_User 1
#define P_Creater 2
class NamePipe
{
public:
    NamePipe(const string& Ipath,int Id)
    :ipath(Ipath),id(Id)
    {
        if (id == P_User)
        {
            fd = open(ipath.c_str(), O_WRONLY);
            if (fd < 0)
                LOG(WARNING, "Userfd error");
        }
        else
        {
            if (mkfifo(ipath.c_str(), 0666) < 0)
            {
                LOG(WARNING, "mkfifo error");
            }
            fd = open(ipath.c_str(), O_RDONLY);
            if (fd < 0)
                LOG(WARNING, "Createrfd error");
        }
        LOG(INFO, to_string(fd));
    }
    void SendMes_To_Pipe(const string &str)
    {
        int n = write(fd, str.c_str(), str.size());
        if (n <= 0)
            LOG(WARNING, "Write error");
    }
    string RecvMes_From_Pipe()
    {
        char buffer[10240] = {0};
        int n = read(fd, buffer, sizeof buffer);
        if(n>0)
        return buffer;
        else
        {
            LOG(WARNING,"write close");
            return "";
        }
    }
    ~NamePipe()
    {
        if (fd >= 0)
        {
            close(fd);
        }
        if(id==P_Creater)
        {
            unlink(ipath.c_str());
        }
    }

private:
    int id;
    string ipath;
    int fd;
};